#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "app_common.h"
#include "stdlib.h"


int  num_sqr(int num)
{   
    sleep(1);
    return num * num;
}

void *num_sqr_thread(void *arg)
{
    sleep(1);
    //1  先强转 int*
    int *num_p = (int *)arg;
    //2  解引用
    int num =  *num_p ;
    //3  创建一个int* 开堆空间
    int *result_p = (int *)malloc(sizeof(int));
    //4 计算 指针指向结果
    *result_p =   num*num;

    return result_p;

}

int main(int argc, char const *argv[])
{
    long start_ts= app_common_get_curtime_ts();
    // 定义一组数
    int numbers[] = {1, 2, 3, 4, 5};
    int result[5];
    int sum=0;
    //平方值
    pthread_t threads[5];
    for (size_t i = 0; i < 5; i++)
    {
       // result[i]=  num_sqr(numbers[i]);
        pthread_create(&threads[i],NULL,num_sqr_thread,&numbers[i]);
        
    }

    for (size_t i = 0; i < 5; i++)
    {   void *result_p;
        pthread_join(threads[i],&result_p);
        //1 强转 int *
         int *result_p_int = (int *)result_p;
         //2 解引用 
         result[i]= *result_p_int;
    }


    //累加
    for (size_t i = 0; i < 5; i++)
    {
        sum+=result[i];
    }
    printf("sum=%d\n",sum);
    printf("time=%ld\n",app_common_get_curtime_ts()-start_ts);
    
    return 0;
}
